<?php

namespace Drupal\shusy_point_product\Entity;

use Drupal\shusy_point_product\ViewsController\Traits\ShusyPointProductStatusTrait;
use Drupal\shusy_point_product\ViewsController\Traits\ShusyPointProductUnitTrait;
use Entity;

class ShusyPointProduct extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $name;

  public $category_id = 0;

  public $point = 0;

  public $sort = 0;

  public $weight = 0;

  public $unit = 0;

  public $status = 0;

  use ShusyPointProductUnitTrait, ShusyPointProductStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_point_product');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    return parent::save();
  }

  function weight() {
    //单位 0 克 1 千克
    switch ($this->unit) {
      case 0:
        return $this->weight;
        break;
      case 1:
        return ceil($this->weight * 1000);
        break;
    }
    return 0;
  }

  function stock() {
    if (!empty($this->id)) {
      $es = shusy_point_product_stock_load_multiple(FALSE, ['point_product_id' => $this->id]);
      if (!empty($es)) {
        $e = reset($es);
        if ($e instanceof ShusyPointProductStock) {
          return $e->stock;
        }
      }
    }
    return 0;
  }

  function stockChange(int $number) {
    if (!empty($this->id)) {
      $es = shusy_point_product_stock_load_multiple(FALSE, ['point_product_id' => $this->id]);
      if (!empty($es)) {
        $e = reset($es);
        if ($e instanceof ShusyPointProductStock) {
          $e->stock += $number;
          $e->save();
        }
      }
    }
  }
}
